package com.dtx.exercise.linkedlist;

import com.dtx.exercise.apiinterface.LineStruct;

public class LinkedList<Item> implements LineStruct<Item> {

    private Node head;

    private Node tail;

    private int size;

    @Override
    public Item add(Item element) {
        Node temp = head;
        Node node = new Node(element);
        if (head==null) {
            head = node;
            tail = node;
        }else {
            while (true){
                if (temp.next==null) {
                    break;
                }
                temp = temp.next;
            }
            temp.next = node;
            tail = node;
        }
        size++;
        return element;
    }

    @Override
    public Item insert(int index, Item element) throws Exception {
        if(index<1 || index>size){
            add(element);
            return element;
        }
        Node insertNode = new Node(element);
        if (size==0) {
            //空链表
        }
        return null;
    }

    @Override
    public Item delete(int index) throws Exception {
        return null;
    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public void output() throws Exception {
        Node temp = head;
        if (isEmpty()) {
            throw new Exception("链表为空");
        }
       while (temp!=null){
           System.out.println(temp.data);
           temp = temp.next;
       }
    }

    @Override
    public Item query(Item element) {
        return null;
    }

    private static class Node<Item>{
        Item data;
        Node next;

        public Node(Item data) {
            this.data = data;
        }
    }

    public boolean isEmpty(){
        return head==null;
    }
}
